//
//  MSWeekStatisticsController.m
//  觅尚
//
//  Created by No.8 on 2019/3/26.
//  Copyright © 2019 No.8. All rights reserved.
//

#import "MSWeekStatisticsController.h"
#import "MSWeekCell.h"
#import "SEQColumnChart.h"
#import "MSWeekStatisticsModel.h"
#import "HQPickerView.h"

@interface MSWeekStatisticsController ()<UITableViewDelegate,UITableViewDataSource,HQPickerViewDelegate>
/** tableView*/
@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *punchCountMapArray;

@property(nonatomic,strong)NSMutableArray *timeArray;

/** 考勤总人数*/
@property(nonatomic,strong)NSString *staffCount;

/** 统计连续三天未出勤人数*/
@property(nonatomic,strong)NSString *userNotList;

/** 统计全勤人数*/
@property(nonatomic,strong)NSString *userFullList;


/** <#name#>*/
@property(nonatomic,strong)UILabel *timeLabel;

/** <#name#>*/
@property(nonatomic,strong)NSString * TimeStr;
@end

@implementation MSWeekStatisticsController
- (int)navBarBottom {
    if ([WRNavigationBar isIphoneX]) {
        return 88;
    } else {
        return 64;
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
    self.punchCountMapArray = [NSMutableArray new];
    self.timeArray = [NSMutableArray new];
    Prepare *header = [Prepare headerWithRefreshingTarget:self refreshingAction:@selector(MJChiBaoZiHeaderRefresh)];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    // 马上进入刷新状态
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
    
    
}
- (void)MJChiBaoZiHeaderRefresh{
    
    [self ReloadData];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = backgroundcolor;
    
//    [self CreatView];
    
    [self tableView];
    
    
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(progressTimer:) userInfo:nil repeats:YES];
}
- (void)ReloadData{
    [self.punchCountMapArray removeAllObjects];
    [self.timeArray removeAllObjects];
    
    if ([self.timeLabel.text isEqualToString:@"第1周"]) {
        self.TimeStr = @"1";
    }else if ([self.timeLabel.text isEqualToString:@"第2周"]) {
        self.TimeStr = @"2";
    }else if ([self.timeLabel.text isEqualToString:@"第3周"]) {
        self.TimeStr = @"3";
    }else if ([self.timeLabel.text isEqualToString:@"第4周"]) {
        self.TimeStr = @"4";
    }else{
        self.TimeStr = @"5";
    }
    
    NSDictionary * params = @{@"busid":[WYCAccountTool unarchivebelongBusid],@"queryTime":@"week",@"depid":[WYCAccountTool unarchivebelongDepid],@"roleId":[WYCAccountTool unarchivebelongRolid],@"dateTime":self.TimeStr};
    WYCLog(@"------%@",params);
    [HTTPRequest POST:MSgetDepartmentAttendance params:params succeed:^(id responseObject) {
        WYCLog(@"------%@",responseObject);
        if (CodeStr) {
            [self.tableView.mj_header endRefreshing];
            [MBManager hideAlert];
//            self.punchCountMapArray = [MSWeekStatisticsModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"punchCountMap"]];
            self.userNotList = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"userNotList"]];
            self.staffCount = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"staffCount"]];
            self.userFullList = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"userFullList"]];
            for (NSDictionary * dict in responseObject[@"data"][@"punchCountMap"]) {
                MSWeekStatisticsModel * model = [MSWeekStatisticsModel mj_objectWithKeyValues:dict];
                [self.punchCountMapArray addObject:model.count];
                NSArray *array = [model.queryTime componentsSeparatedByString:@"-"]; //从字符A中分隔成2个元素的数组
                NSString *queryTimeStr = [NSString stringWithFormat:@"%@",array[2]];
                [self.timeArray addObject:queryTimeStr];
            }
        }else{
            [self.tableView.mj_header endRefreshing];
            [MBManager hideAlert];
            [MBManager showBriefAlert:responseObject[@"msg"]];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [MBManager hideAlert];
        [MBManager showBriefAlert:Failed];
    }];
}
/** 表视图*/
- (UITableView *)tableView{
    self.extendedLayoutIncludesOpaqueBars = YES;
    if (!_tableView) {
        
        if (@available(iOS 11.0, *)) {
            
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        } else {
            
            self.automaticallyAdjustsScrollViewInsets = NO;
            
        }
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - [self navBarBottom] - 150 * px) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = WYCRGBColor(34, 47, 66);
        [self.view addSubview:self.tableView];
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 1200 * px;
    }else{
        return 200 * px;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    MSWeekCell * cell = [MSWeekCell cellWithTableView:tableView];
    tableView.backgroundColor = [UIColor clearColor];
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (indexPath.row == 0) {
        
        UIView * HeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1200 * px)];
        HeaderView.backgroundColor = backgroundcolor;
        [cell.contentView addSubview:HeaderView];
        
        UIView * timeView = [[UIView alloc] initWithFrame:CGRectMake(50 * px, 50 * px, ScreenWidth * 0.71, 120 * px)];
        timeView.layer.cornerRadius = 10 * px;
        timeView.layer.borderWidth = 1;
        timeView.layer.borderColor = WYCRGBColor(33, 46, 45).CGColor;
        [HeaderView addSubview:timeView];
        
        
        /** 日历图标*/
        UIButton * TimeButton = [[UIButton alloc] initWithFrame:CGRectMake(30 * px, 30 * px, 60 * px, 60 * px)];
        //    [TimeButton setImage:[UIImage imageNamed:@"calendar icon"] forState:UIControlStateNormal];
        [TimeButton setBackgroundImage:[UIImage imageNamed:@"calendar icon"] forState:UIControlStateNormal];
        TimeButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        //    TimeButton.backgroundColor = [UIColor redColor];
        [TimeButton addTarget:self action:@selector(showPickerView) forControlEvents:UIControlEventTouchUpInside];
        [timeView addSubview:TimeButton];
        
        /** 左按钮*/
        UIButton *  leftButton= [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(TimeButton.frame) + 40 * px, TimeButton.y, 40 * px, TimeButton.height)];
        [leftButton setBackgroundImage:[UIImage imageNamed:@"日期选择-左箭头"] forState:UIControlStateNormal];
//        [leftButton addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [timeView addSubview:leftButton];
        
        
        
        
        
        NSDate*date = [NSDate date];
        
        
        NSCalendar*calendar = [NSCalendar currentCalendar];
        
        
        NSDateComponents*comps;
        
        comps =[calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit)
                
                
                           fromDate:date];
        
        NSInteger year = [comps year];
        
        NSInteger week = [comps week]; // 今年的第几周
        
        
        NSInteger weekday = [comps weekday]; // 星期几（注意，周日是“1”，周一是“2”。。。。）
        
        
        NSInteger weekdayOrdinal = [comps weekdayOrdinal]; // 这个月的第几周
        
        
        //    NSLog(@"week:%d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);
        
        /** 时间*/
        UILabel * timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftButton.frame) + 40 * px, TimeButton.y, timeView.width / 2, TimeButton.height)];
        timeLabel.textColor = [UIColor grayColor];
        timeLabel.textAlignment = NSTextAlignmentCenter;
        timeLabel.text = [NSString stringWithFormat:@"第%ld周",(long)weekdayOrdinal];
        timeLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
        [timeView addSubview:timeLabel];
        self.timeLabel = timeLabel;
        
        /** 右按钮*/
        UIButton *  rightButton= [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(timeLabel.frame) + 20 * px, TimeButton.y, 40 * px, TimeButton.height)];
        [rightButton setBackgroundImage:[UIImage imageNamed:@"日期选择-右箭头"] forState:UIControlStateNormal];
//        [rightButton addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [timeView addSubview:rightButton];
        
        
        /** 员工*/
        UILabel * staffIMG = [[UILabel alloc] initWithFrame:CGRectMake(HeaderView.width / 4, CGRectGetMaxY(timeView.frame) + 40 * px, 40 * px, 40 * px)];
        staffIMG.layer.cornerRadius = 5 * px;
        staffIMG.backgroundColor = WYCRGBColor(30, 43, 94);
        [HeaderView addSubview:staffIMG];
        
        
        
        /** 员工*/
        UILabel * staffLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(staffIMG.frame) + 20 * px, staffIMG.y - 10 * px, 240 * px, 60 * px)];
        staffLabel.text = @"员工总数";
        staffLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
        staffLabel.textColor = [UIColor whiteColor];
        [HeaderView addSubview:staffLabel];
        
        
        
        /** 员工*/
        UILabel * AttendanceIMG = [[UILabel alloc] initWithFrame:CGRectMake(HeaderView.width / 2 + 40 * px, staffIMG.y, staffIMG.width, staffIMG.height)];
        AttendanceIMG.layer.cornerRadius = 5 * px;
        AttendanceIMG.backgroundColor = WYCRGBColor(242, 193, 78);
        [HeaderView addSubview:AttendanceIMG];
        
        
        
        /** 员工*/
        UILabel * AttendanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(AttendanceIMG.frame) + 20 * px, staffLabel.y, staffLabel.width, staffLabel.height)];
        AttendanceLabel.text = @"出勤人数";
        AttendanceLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
        AttendanceLabel.textColor = [UIColor whiteColor];
        [HeaderView addSubview:AttendanceLabel];
        
        /*        创建对象         */
        SEQColumnChart *column = [[SEQColumnChart alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(timeView.frame) + 50 * px, ScreenWidth, 800 * px)];
        /*        创建数据源数组 每个数组即为一个模块数据 例如第一个数组可以表示某个班级的不同科目的平均成绩 下一个数组表示另外一个班级的不同科目的平均成绩         */
        column.valueArr = self.punchCountMapArray;
//                            @[
//                           @[@"1"],
//                           @[@"1"],
//                           @[@"1"],
//                           @[@"1"],
//                           @[@"1"],
//                           @[@"1"],
//                           @[@"1"]
//                           ];
//
        
        
//        WYCLog(@"=========%@",column.valueArr);
//
//        WYCLog(@"=========%@",self.punchCountMapArray);
        /*       该点 表示原点距左下角的距离         */
        column.originSize = CGPointMake(30, 30);
        
        /*        第一个柱状图距原点的距离         */
        column.drawFromOriginX = 30;
        /*        两组柱状图间距         */
        column.typeSpace = 35;
        /*        柱状图的宽度         */
        column.columnWidth = 10;
        /*        X、Y轴字体颜色         */
        column.drawTextColorForX_Y = [UIColor whiteColor];
        /*        X、Y轴线条颜色         */
        column.colorForXYLine = [UIColor whiteColor];
        
        /*        模块的提示语         */
        column.xShowInfoText = self.timeArray;
//        WYCLog(@"=========%@",self.timeArray);
//        WYCLog(@"=========%@",column.xShowInfoText);
        /*        开始动画         */
        [column showAnimation];
        [cell.contentView addSubview:column];
    }else if (indexPath.row == 1){
        /** 员工标题*/
        UILabel * staffLabel = [[UILabel alloc] initWithFrame:CGRectMake(60 * px, 70 * px, 260 * px, 60 * px)];
        staffLabel.textColor = [UIColor whiteColor];
        staffLabel.text = @"员工总数";
        staffLabel.font = [UIFont systemFontOfSize:SYRealValue(35 / 2)];
        [cell.contentView addSubview:staffLabel];
        
        
        /** 员工标题*/
        UILabel * rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 260 * px, staffLabel.y, 200 * px, staffLabel.height)];
        rightLabel.textColor = staffLabel.textColor;
        rightLabel.text = [NSString stringWithFormat:@"%@人",self.staffCount];
        rightLabel.textAlignment = NSTextAlignmentRight;
        rightLabel.font = [UIFont systemFontOfSize:SYRealValue(35 / 2)];
        [cell.contentView addSubview:rightLabel];
        
    }else if (indexPath.row == 2){
        /** 员工标题*/
        UILabel * CheckLabel = [[UILabel alloc] initWithFrame:CGRectMake(60 * px, 70 * px, 260 * px, 60 * px)];
        CheckLabel.textColor = [UIColor whiteColor];
        CheckLabel.text = @"考勤人数";
        CheckLabel.font = [UIFont systemFontOfSize:SYRealValue(35 / 2)];
        [cell.contentView addSubview:CheckLabel];
        
        
        /** 员工标题*/
        UILabel * CheckrightLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 260 * px, CheckLabel.y, 200 * px, CheckLabel.height)];
        CheckrightLabel.textColor = [UIColor whiteColor];
        CheckrightLabel.text = [NSString stringWithFormat:@"%@人",self.userNotList];
        CheckrightLabel.textAlignment = NSTextAlignmentRight;
        CheckrightLabel.font = [UIFont systemFontOfSize:SYRealValue(35 / 2)];
        [cell.contentView addSubview:CheckrightLabel];
        
    }else{
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        /** 员工标题*/
        UILabel * ThreedayLabel = [[UILabel alloc] initWithFrame:CGRectMake(60 * px, 70 * px, ScreenWidth * 0.5, 60 * px)];
        ThreedayLabel.textColor = [UIColor whiteColor];
        ThreedayLabel.text = @"连续三天未考勤人数";
        ThreedayLabel.font = [UIFont systemFontOfSize:SYRealValue(35 / 2)];
        [cell.contentView addSubview:ThreedayLabel];
        
        
        /** 员工标题*/
        UILabel * ThreedaycountLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 300 * px, ThreedayLabel.y, 200 * px, ThreedayLabel.height)];
        ThreedaycountLabel.textColor = [UIColor whiteColor];
        ThreedaycountLabel.text = [NSString stringWithFormat:@"%@人",self.userNotList];
        ThreedaycountLabel.textAlignment = NSTextAlignmentRight;
        ThreedaycountLabel.font = [UIFont systemFontOfSize:SYRealValue(35 / 2)];
        [cell.contentView addSubview:ThreedaycountLabel];
        
    }
    return cell;
}

- (void)showPickerView {
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    
    NSUInteger numberOfDaysInMonth = range.length;
    
    //    NSLog(@"%lu", (unsigned long)numberOfDaysInMonth);
    HQPickerView *picker = [[HQPickerView alloc]initWithFrame:self.view.bounds];
    picker.delegate = self ;
    
    float dayF = numberOfDaysInMonth / 7;
//    WYCLog(@"-=-------%f",dayF);
    //    CGFloat *
    if (dayF >= 4.0f) {
        picker.customArr = @[@"第1周",@"第2周",@"第3周",@"第4周",@"第5周"];
    }
    else{
        picker.customArr = @[@"第1周",@"第2周",@"第3周",@"第4周"];
    }
    
    [[UIApplication sharedApplication].keyWindow addSubview:picker];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectText:(NSString *)text didSelectStr:(NSString *)ID{
    self.timeLabel.text = [NSString stringWithFormat:@"%@",text];
    [self ReloadData];
}
@end
